#include "pvpwindow.h"
#include "ui_pvpwindow.h"
#include "frmselectpiece.h".h"
#include <qpainter.h>

extern bool gameState;
extern int countWhoFirst;
extern int countPlayer1Use;
extern int gameMode;

PVPWindow::PVPWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PVPWindow)
{
    ui->setupUi(this);

    this->chess=new Chess(ui->widget_chess);
    this->chess->setGeometry(0,0,ui->widget_chess->width(),ui->widget_chess->height());
    gameMode=1;
    connect(this->chess,SIGNAL(start_emit(int,int,int)),this,SLOT(read_emit(int,int,int)));
    connect(this->chess,SIGNAL(postresult_emit(int,int)),this,SLOT(getresult_emit(int,int)));
    this->installEventFilter(this);
}

PVPWindow::~PVPWindow()
{
    delete ui;
}

void PVPWindow::on_btn_start_clicked()
{
    gameState=true;
    FrmSelectPiece *frmChoose=new FrmSelectPiece(this);
    frmChoose->setWindowModality(Qt::WindowModal);
    frmChoose->setWindowTitle("选择棋子");
    frmChoose->show();
    connect(frmChoose,SIGNAL(restart_emit()),this,SLOT(restartGame()));
}

void PVPWindow::on_btn_undo_clicked()
{
    gameState=true;
    this->chess->deleteChessBoardXY();
    update();
}

void PVPWindow::on_btn_giveup_clicked()
{

}

void PVPWindow::read_emit(int num, int score1, int score2)
{
    QString str=QString("Step:%1步").arg(num,10);
    ui->label_step->setText(str);
}

void PVPWindow::getresult_emit(int gamemode, int whoWin)
{
    if(whoWin==1)
    {
        ui->labelResult->setText("玩家1胜利");
    }
    else if(whoWin==2)
    {
        ui->labelResult->setText("玩家2胜利");
    }
    else
    {
        ui->labelResult->setText("玩家1和2平局");
    }
}

void PVPWindow::restartGame()
{
    this->chess->clearChessBoard();
    this->chess->setWhoWin(0);
    ui->label_step->setText(QString("Step:%1步").arg(this->chess->getStep()));
    ui->labelResult->setText("Result");
    ui->btn_start->setText("重新开始");
    update();
}

void PVPWindow::paintEvent(QPaintEvent *)
{
    QPainter *paint=new QPainter;
    paint->begin(this);
    paint->setRenderHint(QPainter::Antialiasing,true);
    paint->setPen(Qt::NoPen);
    QBrush *brush=new QBrush;
    brush->setStyle(Qt::SolidPattern);

    int x1=ui->lbPlayer1->x(),y1=ui->lbPlayer1->y();
    int x2=ui->lbPlayer2->x(),y2=ui->lbPlayer2->y();
    int margin=20;

    if(countPlayer1Use == 0){
        brush->setColor(Qt::black);
        paint->setBrush(*brush);
        paint->drawEllipse(x1,y1+margin,28,28);

        brush->setColor(Qt::white);
        paint->setBrush(*brush);
        paint->drawEllipse(x2,y2+margin,28,28);

    }
    else if(countPlayer1Use == 1){
        brush->setColor(Qt::white);
        paint->setBrush(*brush);
        paint->drawEllipse(x1,y1+margin,28,28);

        brush->setColor(Qt::black);
        paint->setBrush(*brush);
        paint->drawEllipse(x2,y2+margin,28,28);
    }

    paint->end();
}
